package com.work.work.service.impl;

    import com.alibaba.excel.EasyExcel;
    import com.alibaba.excel.ExcelWriter;
    import com.alibaba.excel.write.metadata.WriteSheet;
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import com.work.work.dto.CreateTaskRequest;
    import com.work.work.dto.ProjectReportDTO;
    import com.work.work.dto.ProjectTaskDTO;
    import com.work.work.entity.Progress;
    import com.work.work.entity.Project;
    import com.work.work.entity.Task;
    import com.work.work.mapper.ProgressMapper;
    import com.work.work.mapper.ProjectMapper;
    import com.work.work.mapper.TaskMapper;
    import com.work.work.service.ProjectService;
    import com.work.work.service.TaskService;
    import jakarta.servlet.http.HttpServletResponse;
    import org.springframework.beans.BeanUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    import java.io.IOException;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.net.URLEncoder;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;

@Service
    public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {

    @Autowired
    private ProjectService projectService;
        @Autowired
        private ProgressMapper progressMapper; // 添加这一行
        @Autowired
        private ProjectMapper projectMapper;

        @Override
        @Transactional
        public boolean createTask(CreateTaskRequest request) {
            Task task = new Task();
            BeanUtils.copyProperties(request, task);
            task.setStatus(1); // 1-未开始
            return save(task);
        }


    @Override
    @Transactional
    public boolean updateTaskStatus(Integer taskId, Integer status) {
        // 验证任务是否存在
        Task task = getById(taskId);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }

        // 更新任务状态
        task.setStatus(status);
        boolean success = updateById(task);

        if (success) {
            // 更新对应项目的进度
            projectService.updateProjectProgress(task.getProjectId());
        }

        return success;
    }

        @Override
        public List<ProjectTaskDTO> getProjectTasks(Integer projectId) {
            LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Task::getProjectId, projectId);

            return list(wrapper).stream()
                    .map(task -> {
                        ProjectTaskDTO dto = new ProjectTaskDTO();
                        BeanUtils.copyProperties(task, dto);
                        return dto;
                    })
                    .collect(Collectors.toList());
        }

        @Override
        @Transactional
        public void updateProjectProgress(Integer projectId) {
            // 获取项目所有任务
            List<Task> tasks = list(new LambdaQueryWrapper<Task>()
                    .eq(Task::getProjectId, projectId));

            if (tasks.isEmpty()) {
                return;
            }

            // 计算总权重和已完成权重
            int totalPriority = tasks.stream()
                    .mapToInt(Task::getPriority)
                    .sum();

            int completedPriority = tasks.stream()
                    .filter(task -> task.getStatus() == 3) // 3-已完成
                    .mapToInt(Task::getPriority)
                    .sum();

            // 计算进度
            BigDecimal progress = BigDecimal.valueOf(completedPriority)
                    .divide(BigDecimal.valueOf(totalPriority), 2, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100));

            // 更新项目进度
            Project project = new Project();
            project.setId(projectId);
            project.setProgress(progress);
            projectMapper.updateById(project);
        }



        @Override
        public Page<Task> getTasksByProjectId(Integer projectId, Integer current, Integer size) {
            LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Task::getProjectId, projectId);
            return page(new Page<>(current, size), queryWrapper);
        }

        @Override
        public Page<Task> getTasksByAssignee(String assignee, Integer current, Integer size) {
            LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Task::getAssignee, assignee);
            return page(new Page<>(current, size), queryWrapper);
        }

}